<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="baidu-site-verification" content="WTTWi2XnJ5">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Josefin Sans:300,300italic,400,400italic,700,700italic|Lobster:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"lclong.top","root":"/","scheme":"Gemini","version":"7.7.1","exturl":true,"sidebar":{"position":"left","display":"post","padding":20,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="【多线程】ThreadLocal原理使用12345ThreadLocal&lt;String&gt; threadLocalA&#x3D; new ThreadLocal&lt;String&gt;(); threadLocalA.set(new String(&quot;A&quot;)); String str &#x3D; threadLocalA.get();">
<meta property="og:type" content="article">
<meta property="og:title" content="(转)ThreadLocal原理">
<meta property="og:url" content="https://lclong.top/2018/09/30/(%E8%BD%AC)ThreadLocal%E5%8E%9F%E7%90%86/index.html">
<meta property="og:site_name" content="Zlatanlong&#39;s T-blog">
<meta property="og:description" content="【多线程】ThreadLocal原理使用12345ThreadLocal&lt;String&gt; threadLocalA&#x3D; new ThreadLocal&lt;String&gt;(); threadLocalA.set(new String(&quot;A&quot;)); String str &#x3D; threadLocalA.get();">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2018-09-30T10:53:12.000Z">
<meta property="article:modified_time" content="2018-09-30T10:53:12.000Z">
<meta property="article:author" content="Zlatanlong">
<meta property="article:tag" content="多线程">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://lclong.top/2018/09/30/(%E8%BD%AC)ThreadLocal%E5%8E%9F%E7%90%86/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>(转)ThreadLocal原理 | Zlatanlong's T-blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Zlatanlong's T-blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <h1 class="site-subtitle" itemprop="description">Lakers is Championship!</h1>
      
  </div>

  <div class="site-nav-right"></div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">31</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类<span class="badge">23</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">38</span></a>

  </li>
        <li class="menu-item menu-item-aboutme">

    <a href="/aboutme/" rel="section"><i class="fa fa-fw fa-user"></i>博主</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://lclong.top/2018/09/30/(%E8%BD%AC)ThreadLocal%E5%8E%9F%E7%90%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Zlatanlong">
      <meta itemprop="description" content="生活就像巧克力🍫">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Zlatanlong's T-blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          (转)ThreadLocal原理
        </h2>

        <div class="post-meta">
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-09-30 18:53:12" itemprop="dateCreated datePublished" datetime="2018-09-30T18:53:12+08:00">2018-09-30</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>
            </span>

          
            <span id="/2018/09/30/(%E8%BD%AC)ThreadLocal%E5%8E%9F%E7%90%86/" class="post-meta-item leancloud_visitors" data-flag-title="(转)ThreadLocal原理" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">评论次数：</span>
    
    <a title="valine" href="/2018/09/30/(%E8%BD%AC)ThreadLocal%E5%8E%9F%E7%90%86/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2018/09/30/(%E8%BD%AC)ThreadLocal%E5%8E%9F%E7%90%86/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>3.1k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>8 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="【多线程】ThreadLocal原理"><a href="#【多线程】ThreadLocal原理" class="headerlink" title="【多线程】ThreadLocal原理"></a>【多线程】ThreadLocal原理</h1><h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">ThreadLocal&lt;String&gt; threadLocalA= <span class="keyword">new</span> ThreadLocal&lt;String&gt;(); </span><br><span class="line"></span><br><span class="line">threadLocalA.set(<span class="keyword">new</span> String(<span class="string">"A"</span>)); </span><br><span class="line"></span><br><span class="line">String str = threadLocalA.get();</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<h2 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h2><p>在每个线程的内部有个数据结构为<code>Map</code>的<code>threadLocals</code>变量，以<code>&lt;ThreadLocal,Value&gt;</code>的形式保存着线程变量和其对应的值。</p>
<p>当使用<code>set()</code>方法时：</p>
<ol>
<li>获取到当前线程的<code>threadLocals</code>，类型为<code>Map</code></li>
<li>将这值放到这个<code>Map</code>结构的变量中，key为ThreadLocal对象，value为所有存放的值</li>
</ol>
<p>当使用<code>get()</code>方法时：</p>
<ol>
<li>获取到当前线程的<code>threadLocals</code>，类型为<code>Map</code>。</li>
<li>以<code>ThreadLocal</code>对象为Map的key获取到它的<code>value</code>值。</li>
</ol>
<p>因为ThreadLocal对象作为Map的key，所以一个ThreadLocal对象只能存放一个值，当存放多个时，会将新值覆盖旧值。</p>
<h2 id="源码"><a href="#源码" class="headerlink" title="源码"></a>源码</h2><p>数据结构：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">set</span><span class="params">(T value)</span> </span>&#123; </span><br><span class="line"></span><br><span class="line">Thread t = Thread.currentThread();</span><br><span class="line"></span><br><span class="line">ThreadLocalMap map = getMap(t);<span class="comment">//当前线程为入参，获取当前线程的threadLocals变量 </span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (map != <span class="keyword">null</span>) </span><br><span class="line"></span><br><span class="line"><span class="comment">//入参为this，也就是说key为ThreadLocal对象</span></span><br><span class="line"></span><br><span class="line">map.set(<span class="keyword">this</span>, value);</span><br><span class="line"></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line"></span><br><span class="line">createMap(t, value);</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> T <span class="title">get</span><span class="params">()</span> </span>&#123; </span><br><span class="line"></span><br><span class="line">Thread t = Thread.currentThread();</span><br><span class="line"></span><br><span class="line">ThreadLocalMap map = getMap(t);<span class="comment">//当前线程为入参，获取当前线程的threadLocals </span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (map != <span class="keyword">null</span>) &#123; </span><br><span class="line"></span><br><span class="line"><span class="comment">//入参为this，也就是说key为ThreadLocal</span></span><br><span class="line"></span><br><span class="line">ThreadLocalMap.Entry e = map.getEntry(<span class="keyword">this</span>); </span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (e != <span class="keyword">null</span>) &#123; </span><br><span class="line"></span><br><span class="line"><span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line"></span><br><span class="line">T result = (T)e.value;</span><br><span class="line"></span><br><span class="line"><span class="keyword">return</span> result; </span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">return</span> setInitialValue(); </span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function">ThreadLocalMap <span class="title">getMap</span><span class="params">(Thread t)</span> </span>&#123; </span><br><span class="line"></span><br><span class="line"><span class="keyword">return</span> t.threadLocals;<span class="comment">//threadLocals为线程的变量 </span></span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> Entry <span class="title">getEntry</span><span class="params">(ThreadLocal&lt;?&gt; key)</span> </span>&#123; </span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> i = key.threadLocalHashCode &amp; (table.length - <span class="number">1</span>); </span><br><span class="line"></span><br><span class="line">Entry e = table[i];</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (e != <span class="keyword">null</span> &amp;&amp; e.get() == key) </span><br><span class="line"></span><br><span class="line"><span class="keyword">return</span> e; </span><br><span class="line"></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">return</span> getEntryAfterMiss(key, i, e);<span class="comment">//避免内存泄漏，下文有提。 </span></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="内存泄漏"><a href="#内存泄漏" class="headerlink" title="内存泄漏"></a>内存泄漏</h2><p>ThreadLocalMap结构如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">ThreadLocalMap</span> </span>&#123; </span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">```</span></span><br><span class="line"><span class="comment">* The entries in this hash map extend WeakReference, using</span></span><br><span class="line"><span class="comment">* its main ref field as the key (which is always a</span></span><br><span class="line"><span class="comment">* ThreadLocal object). Note that null keys (i.e. entry.get()</span></span><br><span class="line"><span class="comment">* == null) mean that the key is no longer referenced, so the</span></span><br><span class="line"><span class="comment">* entry can be expunged from table. Such entries are referred to</span></span><br><span class="line"><span class="comment">* as "stale entries" in the code that follows.</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">```</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Entry</span> <span class="keyword">extends</span> <span class="title">WeakReference</span>&lt;<span class="title">ThreadLocal</span>&lt;?&gt;&gt; </span>&#123; </span><br><span class="line"></span><br><span class="line">Object value; </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Entry(ThreadLocal&lt;?&gt; k, Object v) &#123; </span><br><span class="line"></span><br><span class="line"><span class="keyword">super</span>(k); <span class="comment">//key，这个是一个弱引用，如果没有强引用来引用key(也就是ThreadLocal)，则key会被回收，形成了key为null的Entry。 </span></span><br><span class="line"></span><br><span class="line">value = v;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> Entry[] table;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>threadLocals变量是在线程内部的，故没有多个线程去访问它，所以不存在线程不安全的说法，同时只要线程被回收了就不会存在内存泄漏。</p>
<p>ThreadLocal对象被回收时(key为null)，没有办法获取到value，而线程又不会被回收时则value一直占用空间导致内存泄漏。线程不会被回收的常见场景是线程池。</p>
<p>JDK在此做了一个优化，在调用get(),set(),remove()方法会做额外处理来清理ThreadLocalMap中key为null的value，以减少内存泄漏的影响。但是如果key未使用弱引用，即使ThreadLocal被回收了，key也不为null，也就是说是没法判断哪个value需要回收的，最终造成内存泄漏。所以此处的弱引用key是内存泄漏的一个优化处理方式。</p>
<h2 id="使用场景"><a href="#使用场景" class="headerlink" title="使用场景"></a>使用场景</h2><p>在实际项目中，可以用来减少同一个线程内多个函数或者组件之间一些公共变量的传递的复杂度，因为servlet是单例多线程的，每个请求执行的操作都是同一个线程中。比如：可以用ThreadLocal来存每一次请求用户的信息，定义了一个类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserContextHolder</span></span>&#123; </span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> ThreadLocal&lt;User&gt; userContextHolder = <span class="keyword">new</span> ThreadLocal&lt;&gt;(); </span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="title">setUser</span><span class="params">(User user)</span></span>&#123; </span><br><span class="line"></span><br><span class="line">userContextHolder.set(user);</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> User <span class="title">getUser</span><span class="params">()</span></span>&#123; </span><br><span class="line"></span><br><span class="line"><span class="keyword">return</span> userContextHolder.get(); </span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">remove</span><span class="params">()</span></span>&#123; </span><br><span class="line"></span><br><span class="line"><span class="keyword">return</span> userContextHolder.remove(); </span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当用户每次请求进来时，在拦截器中获取用户信息调用<code>UserContextHolder.setUser()</code>将其放到<code>userContext</code>中，无论在哪我们只要调用<code>UserContextHolder.getUser()</code>可以很轻松的获取到用户的信息，而不用在函数调用时一层一层的传递。同时在拦截器结束时调用<code>UserContextHolder.remove()</code>移除掉即可。</p>
<blockquote>
<p>转载自简书: <span class="exturl" data-url="aHR0cHM6Ly93d3cuamlhbnNodS5jb20vdS9hMGU5YjdjMzZmZGQ=" title="https://www.jianshu.com/u/a0e9b7c36fdd">eejron<i class="fa fa-external-link"></i></span></p>
</blockquote>

    </div>

    
    
    
      

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Zlatanlong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://lclong.top/2018/09/30/(%E8%BD%AC)ThreadLocal%E5%8E%9F%E7%90%86/" title="(转)ThreadLocal原理">https://lclong.top/2018/09/30/(转)ThreadLocal原理/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <span class="exturl" data-url="aHR0cHM6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL2xpY2Vuc2VzL2J5LW5jLXNhLzQuMC96aC1DTg=="><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</span> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" rel="tag"><i class="fa fa-tag"></i> 多线程</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2018/09/13/(%E8%BD%AC)vue%E6%89%93%E5%8C%85%E5%8E%8B%E7%BC%A9%E4%BD%93%E7%A7%AF/" rel="prev" title="(转)vue打包压缩体积">
      <i class="fa fa-chevron-left"></i> (转)vue打包压缩体积
    </a></div>
      <div class="post-nav-item">
    <a href="/2018/10/07/(%E8%BD%AC)java%20List%20%E6%8E%92%E5%BA%8F%20Collections.sort()/" rel="next" title="(转)Java List 排序 Collections.sort()">
      (转)Java List 排序 Collections.sort() <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  
  </div>


          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#【多线程】ThreadLocal原理"><span class="nav-number">1.</span> <span class="nav-text">【多线程】ThreadLocal原理</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#使用"><span class="nav-number">1.1.</span> <span class="nav-text">使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#原理"><span class="nav-number">1.2.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#源码"><span class="nav-number">1.3.</span> <span class="nav-text">源码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#内存泄漏"><span class="nav-number">1.4.</span> <span class="nav-text">内存泄漏</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用场景"><span class="nav-number">1.5.</span> <span class="nav-text">使用场景</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Zlatanlong"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Zlatanlong</p>
  <div class="site-description" itemprop="description">生活就像巧克力🍫</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">38</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">23</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">31</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL3psYXRhbmxvbmc=" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;zlatanlong"><i class="fa fa-fw fa-github"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="bWFpbHRvOmxvbmctdHhnY0Bmb3htYWlsLmNvbQ==" title="E-Mail → mailto:long-txgc@foxmail.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      关注列表
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly9sZWZsYWNvbi5naXRodWIuaW8v" title="https:&#x2F;&#x2F;leflacon.github.io&#x2F;">leflacon</span>
        </li>
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly9ib2Jib3NzLmdpdGh1Yi5pby8=" title="https:&#x2F;&#x2F;bobboss.github.io&#x2F;">BobBoss</span>
        </li>
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cDovL29wdGltaXN0aWNhdC54eXovdXNlcj91c2VySWQ9bHpkY2w=" title="http:&#x2F;&#x2F;optimisticat.xyz&#x2F;user?userId&#x3D;lzdcl">lzdcl</span>
        </li>
    </ul>
  </div>

      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 2018 – 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Zlatanlong</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">166k</span>
</div>
  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> 强力驱动 v4.2.1
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Gemini</span> v7.7.1
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script color='0,0,255' opacity='0.5' zIndex='-1' count='99' src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-nest@latest/canvas-nest-nomobile.min.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'H5inyassVpcpItLTuMJH9aBg-gzGzoHsz',
      appKey     : 'mBzB6QB3deD6zw8YEIKVQdzz',
      placeholder: "快来说两句吧。。。",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
